package net.touchcapture.qr.flutterqr;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;

import com.journeyapps.barcodescanner.BarcodeView;

/**
 * 扫描预览页面
 * Created by liaoyacheng on 2021/7/19.
 */
public class ScanView extends BarcodeView {

    public ScanView(Context context) {
        super(context);
    }

    public ScanView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ScanView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    ///扫描区：上下迁移，正值向上移动，负值向下移动
    protected int scanAreaOffset;
    // Framing rectangle relative to this view
    protected Rect _framingRect = null;
    // Framing rectangle relative to the preview resolution
    protected Rect _previewFramingRect = null;

    /**
     * 扫描区：上下迁移
     * @param scanAreaOffset 正值向上移动，负值向下移动
     */
    public void setScanAreaOffset(int scanAreaOffset) {
        if(this.scanAreaOffset != scanAreaOffset){
            this.scanAreaOffset = scanAreaOffset;
            _framingRect = null;
            _previewFramingRect = null;
        }
    }

    @Override
    public Rect getFramingRect() {
        if(_framingRect == null){
            Rect rect = super.getFramingRect();
            _framingRect =rect == null ? null: offset(rect);
        }
        return _framingRect;
    }

    private Rect offset(Rect target){
        Rect rect = new Rect(target);
        //取负值
        rect.offset(0, -scanAreaOffset);
        if(rect.top <= 0)rect.top = 0;
        if(rect.top >= getHeight())rect.top = getHeight();
        if(rect.bottom <= 0)rect.bottom = 0;
        if(rect.bottom >= getHeight())rect.bottom = getHeight();
        return rect;
    }

    @Override
    public Rect getPreviewFramingRect() {
        if(_previewFramingRect == null){
            Rect rect = super.getPreviewFramingRect();
            _previewFramingRect = rect == null ? null : offset(rect);
            Log.d("flutter","getPreviewFramingRect scanAreaOffset="+scanAreaOffset
                    +",old=" +rect+",new="+_previewFramingRect
                    +",framingRect=" + _framingRect
                    +",w="+getWidth()+",h"+getHeight());
        }
        return _previewFramingRect;
    }
}
